#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/1/7 14:10
# @Author  : HYCX-AI-LAB Liang jinhao

"""
"""
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/9/18 10:27
# @Author  : HYCX-AI-LAB Liang jinhao



from utils.MQ.message import send_message
import json
import datetime
import os
import os.path as osp
from multiprocessing import Process, Queue

from utils.camera.camera_utils import change_programNo, get_camera_data,clear_memory,\
    DATA_DIR, DATA_BACKUP_DIR
camera_multiprocess_queue = Queue()
timeout_sec_clear = 0.1
timeout_sec = 3


class Keyence_Camera():
    def __init__(self,MQ_send, connection_send, task_id, task_type, programNo_set=None, dmc=None, direction=None):
        # MQ
        self.MQ_send = MQ_send
        self.connection_send = connection_send

        self.task_id = task_id
        self.task_type = task_type


        self.programNo_set = programNo_set
        self.dmc = dmc
        self.direction = direction



    def change_pro_no(self):
        if self.programNo_set is None:
            raise ValueError("the programNo_set is None")
        res_dict = {}
        try:
            change_programNo_req = Process(target=change_programNo, args=((self.programNo_set, camera_multiprocess_queue)))
            change_programNo_req.start()
            change_programNo_res = camera_multiprocess_queue.get()
            non_req_process = Process(target=get_camera_data, args=(('', '', timeout_sec_clear, camera_multiprocess_queue)))
            non_req_process.start()
            non_res = camera_multiprocess_queue.get()
            print(non_res)
            res_dict = change_programNo_res
        except Exception as e:
            res_dict["error info"] = e
        finally:
            res_dict["task_id"] = self.task_id
            res_dict["task_type"] = "Camera No. Change"
            send_message(self.MQ_send, self.connection_send, json.dumps(res_dict, ensure_ascii=False))

    def get_camera_data(self):
        if self.dmc is None:
            raise ValueError("the dmc is None")
        if self.direction is None:
            raise ValueError("the direction is None")
        import re
        self.dmc = re.sub(u'\x00', '', self.dmc)
        if self.direction == 1:
            direction_name = '_up'
        else:
            direction_name = '_side'

        file_name = DATA_DIR + self.dmc + direction_name

        current_data = datetime.datetime.now().strftime('%Y-%m-%d')
        dir_name = osp.join(DATA_BACKUP_DIR, current_data)
        if not osp.exists(dir_name):
            os.mkdir(dir_name)
        now_time = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
        backup_file_name = dir_name + '/' + self.dmc + direction_name + '_' + now_time
        res_dict = {}
        try:
            data_req_process = Process(target=get_camera_data,
                                       args=((file_name, backup_file_name, timeout_sec, camera_multiprocess_queue)))
            data_req_process.start()
            res_dict = camera_multiprocess_queue.get()
            print(res_dict)
            clean_req_process = Process(target=clear_memory)
            clean_req_process.start()
        except Exception as e:
            res_dict["error info"] = e
        finally:
            res_dict["task_id"] = self.task_id
            res_dict["task_type"] = "Camera Data Get"
            send_message(self.MQ_send, self.connection_send, json.dumps(res_dict, ensure_ascii=False))

